// 全局变量
let currentPage = 1;
let totalPages = 1;
let currentLimit = 25;
let currentSearch = '';
let currentCategory = '';
let currentMinPrice = '';
let currentMaxPrice = '';
let currentPriceNone = false;
let currentFeatures = [{name: '', value: ''}];

// DOM 加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 获取 DOM 元素
    const searchInput = document.getElementById('searchInput');
    const searchBtn = document.getElementById('searchBtn');
    const resetBtn = document.getElementById('resetBtn');
    const limitSelect = document.getElementById('limitSelect');
    const productsTable = document.getElementById('productsTable');
    const tbody = productsTable.querySelector('tbody');
    
    // 分页按钮
    const firstPageBtn = document.getElementById('firstPage');
    const prevPageBtn = document.getElementById('prevPage');
    const nextPageBtn = document.getElementById('nextPage');
    const lastPageBtn = document.getElementById('lastPage');
    
    // 新增的搜索元素
    const categoryInput = document.getElementById('categoryInput');
    const minPriceInput = document.getElementById('minPrice');
    const maxPriceInput = document.getElementById('maxPrice');
    const priceNoneCheckbox = document.getElementById('priceNoneCheckbox');
    const featureContainer = document.getElementById('featureContainer');
    
    // 绑定事件监听器
    searchBtn.addEventListener('click', searchProducts);
    resetBtn.addEventListener('click', resetSearch);
    limitSelect.addEventListener('change', changeLimit);
    
    firstPageBtn.addEventListener('click', goToFirstPage);
    prevPageBtn.addEventListener('click', goToPrevPage);
    nextPageBtn.addEventListener('click', goToNextPage);
    lastPageBtn.addEventListener('click', goToLastPage);
    
    // 为新增的搜索框添加事件监听器
    categoryInput.addEventListener('input', function() {
        currentCategory = categoryInput.value;
        currentPage = 1;
        loadProducts();
    });
    
    minPriceInput.addEventListener('input', function() {
        currentMinPrice = minPriceInput.value;
        currentPage = 1;
        loadProducts();
    });
    maxPriceInput.addEventListener('input', function() {
        currentMaxPrice = maxPriceInput.value;
        currentPage = 1;
        loadProducts();
    });
    
    priceNoneCheckbox.addEventListener('change', function() {
        currentPriceNone = priceNoneCheckbox.checked;
        currentPage = 1;
        loadProducts();
    });
    
    // 初始化特性输入框事件
    initFeatureInputs();
    
    // 回车键搜索
    searchInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            searchProducts();
        }
    });
    
    // 初始加载数据
    loadProducts();
});

// 初始化特性输入框
function initFeatureInputs() {
    const featureContainer = document.getElementById('featureContainer');
    const addButtons = featureContainer.querySelectorAll('.add-feature');
    
    // 为现有的添加按钮绑定事件
    addButtons.forEach(button => {
        button.addEventListener('click', addFeatureInput);
    });
    
    // 为现有的输入框绑定事件
    const featureNameInputs = featureContainer.querySelectorAll('.featureName');
    const featureValueInputs = featureContainer.querySelectorAll('.featureValue');
    
    featureNameInputs.forEach(input => {
        input.addEventListener('input', function() {
            collectFeatures();
            currentPage = 1;
            loadProducts();
        });
    });
    
    featureValueInputs.forEach(input => {
        input.addEventListener('input', function() {
            collectFeatures();
            currentPage = 1;
            loadProducts();
        });
    });
}

// 添加特性输入框组
function addFeatureInput(e) {
    const featureContainer = document.getElementById('featureContainer');
    const inputGroup = document.createElement('div');
    inputGroup.className = 'feature-input-group';
    
    inputGroup.innerHTML = `
        <input type="text" class="featureName" placeholder="特性名称">
        <input type="text" class="featureValue" placeholder="特性值">
        <button type="button" class="add-feature">+</button>
        <button type="button" class="remove-feature">-</button>
    `;
    
    featureContainer.appendChild(inputGroup);
    
    // 为新添加的按钮绑定事件
    const addButton = inputGroup.querySelector('.add-feature');
    const removeButton = inputGroup.querySelector('.remove-feature');
    const nameInput = inputGroup.querySelector('.featureName');
    const valueInput = inputGroup.querySelector('.featureValue');
    
    addButton.addEventListener('click', addFeatureInput);
    removeButton.addEventListener('click', function() {
        featureContainer.removeChild(inputGroup);
        collectFeatures();
        currentPage = 1;
        loadProducts();
    });
    
    nameInput.addEventListener('input', function() {
        collectFeatures();
        currentPage = 1;
        loadProducts();
    });
    
    valueInput.addEventListener('input', function() {
        collectFeatures();
        currentPage = 1;
        loadProducts();
    });
    
    collectFeatures();
}

// 收集所有特性名称和值
function collectFeatures() {
    const featureNameInputs = document.querySelectorAll('.featureName');
    const featureValueInputs = document.querySelectorAll('.featureValue');
    
    currentFeatures = [];
    for (let i = 0; i < featureNameInputs.length; i++) {
        const name = featureNameInputs[i].value.trim();
        const value = featureValueInputs[i].value.trim();
        if (name !== '' || value !== '') {
            currentFeatures.push({name: name, value: value});
        }
    }
}

// 搜索产品
function searchProducts() {
    const searchInput = document.getElementById('searchInput');
    currentSearch = searchInput.value.trim();
    currentPage = 1;
    loadProducts();
}

// 重置搜索
function resetSearch() {
    const searchInput = document.getElementById('searchInput');
    const categoryInput = document.getElementById('categoryInput');
    const minPriceInput = document.getElementById('minPrice');
    const maxPriceInput = document.getElementById('maxPrice');
    const priceNoneCheckbox = document.getElementById('priceNoneCheckbox');
    const featureNameInputs = document.querySelectorAll('.featureName');
    const featureValueInputs = document.querySelectorAll('.featureValue');
    
    searchInput.value = '';
    categoryInput.value = '';
    minPriceInput.value = '';
    maxPriceInput.value = '';
    priceNoneCheckbox.checked = false;
    
    // 保留一个特性输入框组，清空其余的
    for (let i = 1; i < featureNameInputs.length; i++) {
        featureNameInputs[i].closest('.feature-input-group').remove();
    }
    featureNameInputs[0].value = '';
    featureValueInputs[0].value = '';
    
    currentSearch = '';
    currentCategory = '';
    currentMinPrice = '';
    currentMaxPrice = '';
    currentPriceNone = false;
    currentFeatures = [{name: '', value: ''}];
    currentPage = 1;
    loadProducts();
}

// 改变每页显示数量
function changeLimit() {
    const limitSelect = document.getElementById('limitSelect');
    currentLimit = parseInt(limitSelect.value);
    currentPage = 1;
    loadProducts();
}

// 跳转到第一页
function goToFirstPage() {
    currentPage = 1;
    loadProducts();
}

// 跳转到上一页
function goToPrevPage() {
    if (currentPage > 1) {
        currentPage--;
        loadProducts();
    }
}

// 跳转到下一页
function goToNextPage() {
    if (currentPage < totalPages) {
        currentPage++;
        loadProducts();
    }
}

// 跳转到最后一页
function goToLastPage() {
    currentPage = totalPages;
    loadProducts();
}

// 加载产品数据
function loadProducts() {
    // 收集当前的特性
    collectFeatures();
    
    // 构建查询参数
    const params = new URLSearchParams();
    params.append('page', currentPage);
    params.append('limit', currentLimit);
    
    // 添加基本搜索参数
    if (currentSearch) {
        params.append('search', currentSearch);
    }
    
    // 添加类别搜索参数
    if (currentCategory) {
        params.append('category', currentCategory);
    }
    
    // 添加价格区间参数
    if (currentMinPrice !== '') {
        params.append('minPrice', currentMinPrice);
    }
    if (currentMaxPrice !== '') {
        params.append('maxPrice', currentMaxPrice);
    }
    // 添加价格为 None 的搜索参数
    if (currentPriceNone) {
        params.append('priceNone', 'true');
    }
    
    // 添加特性参数
    if (currentFeatures.length > 0) {
        // 过滤掉空的特性
        const nonEmptyFeatures = currentFeatures.filter(f => f.name !== '' || f.value !== '');
        if (nonEmptyFeatures.length > 0) {
            params.append('features', JSON.stringify(nonEmptyFeatures));
        }
    }
    
    // 发起 API 请求
    fetch(`/api/products?${params.toString()}`)
        .then(response => response.json())
        .then(data => {
            // 更新全局变量
            totalPages = data.pages;
            
            // 更新表格数据
            updateTable(data.products);
            
            // 更新分页信息
            updatePagination(data);
            
            // 更新结果计数
            updateResultsCount(data);
        })
        .catch(error => {
            console.error('获取产品数据时出错:', error);
            alert('获取数据时出错，请查看控制台了解详情。');
        });
}

// 更新表格数据
function updateTable(products) {
    const tbody = document.querySelector('#productsTable tbody');
    tbody.innerHTML = '';
    
    if (products.length === 0) {
        const row = document.createElement('tr');
        row.innerHTML = '<td colspan="5" style="text-align: center;">没有找到匹配的产品</td>';
        tbody.appendChild(row);
        return;
    }
    
    products.forEach(product => {
        const row = document.createElement('tr');
        
        // 处理产品字段，确保它们存在
        const name = product.name || 'N/A';
        const price = product.price || 'N/A';
        const category = product.category || 'N/A';
        const url = product.url || '#';
        
        // 创建特性列表
        let featuresHTML = 'N/A';
        if (product.feature && typeof product.feature === 'object') {
            // 如果用户指定了要显示的特性名称，则只显示这些特性
            let featuresToShow;
            const featureNames = currentFeatures
                .filter(f => f.name !== '')
                .map(f => f.name);
                
            if (featureNames.length > 0) {
                // 只显示指定的特性
                featuresToShow = Object.entries(product.feature).filter(([key, value]) => 
                    featureNames.some(name => key.includes(name))
                );
            } else {
                // 显示所有特性
                featuresToShow = Object.entries(product.feature);
            }
            
            if (featuresToShow.length > 0) {
                const featuresList = featuresToShow
                    .map(([key, value]) => `<li><strong>${escapeHtml(key)}</strong> ${escapeHtml(value)}</li>`)
                    .join('');
                featuresHTML = `<ul class="features-list">${featuresList}</ul>`;
            }
        } else if (product.feature) {
            featuresHTML = escapeHtml(String(product.feature));
        }
        
        row.innerHTML = `
            <td>${escapeHtml(name)}</td>
            <td class="price-cell">${escapeHtml(price)}</td>
            <td>${escapeHtml(category)}</td>
            <td class="features-cell">${featuresHTML}</td>
            <td><a href="${escapeHtml(url)}" target="_blank" class="product-link">查看产品</a></td>
        `;
        
        tbody.appendChild(row);
    });
}

// 更新分页控件
function updatePagination(data) {
    const firstPageBtn = document.getElementById('firstPage');
    const prevPageBtn = document.getElementById('prevPage');
    const nextPageBtn = document.getElementById('nextPage');
    const lastPageBtn = document.getElementById('lastPage');
    const pageInfo = document.getElementById('pageInfo');
    
    // 更新按钮状态
    firstPageBtn.disabled = currentPage === 1;
    prevPageBtn.disabled = currentPage === 1;
    nextPageBtn.disabled = currentPage === data.pages || data.pages === 0;
    lastPageBtn.disabled = currentPage === data.pages || data.pages === 0;
    
    // 更新页面信息
    if (data.total > 0) {
        const start = (currentPage - 1) * currentLimit + 1;
        const end = Math.min(currentPage * currentLimit, data.total);
        pageInfo.textContent = `第 ${currentPage} 页，共 ${data.pages} 页 (${start}-${end} of ${data.total})`;
    } else {
        pageInfo.textContent = '第 1 页，共 1 页 (0 results)';
    }
}

// 更新结果计数
function updateResultsCount(data) {
    const resultsCount = document.getElementById('resultsCount');
    resultsCount.textContent = `显示 ${data.products.length} 条结果，共 ${data.total} 条`;
}

// 转义 HTML 特殊字符以防止 XSS
function escapeHtml(text) {
    const map = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
    };
    
    return String(text).replace(/[&<>"']/g, function(m) { return map[m]; });
}